<template>
  <div ref="radar" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script setup>
import * as echarts from 'echarts/core'
import { TitleComponent, LegendComponent } from 'echarts/components'
import { RadarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { TooltipComponent } from 'echarts/components'
import { debounce } from 'lodash'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import 'echarts/theme/macarons'

echarts.use([TitleComponent, LegendComponent, RadarChart, CanvasRenderer, TooltipComponent])

const animationDuration = 2000

defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
})

let chart = null
const radar = ref(null)

function initChart() {
  chart = echarts.init(radar.value, 'macarons')

  chart.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    radar: {
      radius: '66%',
      center: ['50%', '50%'],
      splitNumber: 8,
      splitArea: {
        areaStyle: {
          color: 'rgba(127,95,132,.3)',
          opacity: 1,
          shadowBlur: 45,
          shadowColor: 'rgba(0,0,0,.5)',
          shadowOffsetX: 0,
          shadowOffsetY: 15
        }
      },
      indicator: [
        { name: '逻辑思维' },
        { name: '项目相关' },
        { name: '基础知识' },
        { name: '理论基础' },
        { name: '高阶技术' }
      ]
    },
    series: [
      {
        type: 'radar',
        symbolSize: 0,
        areaStyle: {
          shadowBlur: 5,
          shadowColor: 'rgba(0,0,0,.2)',
          shadowOffsetX: 0,
          shadowOffsetY: 10,
          opacity: 1
        },
        data: [
          {
            value: [13000, 12000, 10000, 11000, 10000],
            name: 'Allocated Budget'
          }
        ],
        animationDuration: animationDuration
      }
    ]
  })
}

const __resizeHandler = debounce(() => {
  if (chart) {
    chart.resize()
  }
}, 100)
onMounted(() => {
  initChart()

  window.addEventListener('resize', __resizeHandler)
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  window.removeEventListener('resize', __resizeHandler)
  chart.dispose()
  chart = null
})
</script>
